# 大语言模型接口模块 - 增强版
import os
import json
import time
import traceback
import re
import subprocess
import platform
import tempfile
import datetime  # 添加datetime导入
from config import API_KEY, API_BASE_URL, USE_LOCAL_LLM, LLM_MODEL

# 尝试导入OpenAI库，失败时提供友好提示
try:
    from openai import OpenAI
except ImportError:
    print("提示: 未安装OpenAI库，将使用本地大模型或命令解析器。")
    print("要使用OpenAI API，请运行pip install openai")
    OpenAI = None

# 尝试导入transformers库用于本地大模型
try:
    from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
    import torch
    HAS_LOCAL_LLM_SUPPORT = True
except ImportError:
    print("提示: 未安装transformers库，无法使用本地大模型。")
    print("要使用本地大模型，请运行pip install transformers torch")
    HAS_LOCAL_LLM_SUPPORT = False

class LLMInterface:
    def __init__(self):
        # 初始化状态变量
        self.has_valid_key = False
        self.has_local_llm = False
        self.local_llm_pipeline = None
        self.tokenizer = None
        self.model = None
        self.command_history = []
        self.last_used_method = "none"
        
        # 新增系统信息缓存和命令历史增强
        self.system_info = self._get_system_info()
        self.recent_commands = []
        self.max_recent_commands = 10
        
        # 对话上下文管理 - 新增
        self.conversation_history = []
        from config import MAX_CONTEXT_LENGTH, ENABLE_CONVERSATION_CONTEXT, USE_MIXED_MODE, LLM_TIMEOUT
        self.max_context_length = MAX_CONTEXT_LENGTH
        self.enable_conversation = ENABLE_CONVERSATION_CONTEXT
        self.use_mixed_mode = USE_MIXED_MODE
        self.llm_timeout = LLM_TIMEOUT
        
        # 用户偏好和记忆
        self.user_preferences = {}
        self.task_memory = []
        self.conversation_style = "default"  # 默认对话风格
        
        # 对话风格模板
        self.style_templates = {
            "default": "简洁专业",
            "friendly": "友好亲切",
            "technical": "技术详细",
            "concise": "简洁明了",
            "detailed": "详细解释"
        }
        
        # 任务类型识别配置
        self.task_type_patterns = {
            "information_query": [r"什么是", r"解释", r"说明", r"含义", r"定义", r"介绍", r"如何", r"怎么"],
            "task_execution": [r"打开", r"关闭", r"创建", r"删除", r"移动", r"复制", r"运行", r"执行"],
            "conversation": [r"你好", r"嗨", r"早上好", r"晚上好", r"聊天", r"交流"],
            "creative_generation": [r"写", r"创作", r"生成", r"编", r"设计", r"制作"],
            "problem_solving": [r"错误", r"问题", r"故障", r"解决", r"修复", r"帮助"]
        }
        
        # 初始化默认用户偏好
        self._init_user_preferences()
        
        # 系统指令模板，用于指导LLM的行为
        self.system_prompt = """你是一个智能助手，负责解析用户的自然语言指令并执行相应操作。
        1. 你需要识别用户的意图，并将其映射到系统支持的命令上。
        2. 支持的命令类型包括：open_application, close_application, create_folder, list_files, search_files, control_volume, control_brightness, shutdown, restart, sleep, system_info, calculator, screenshot
        3. 对于每个命令，请提取必要的参数并返回json格式，格式为：{"command": "命令类型", "parameters": {"参数名": "参数值"}, "confidence": 置信度(0-1)}
        4. 如果无法识别为具体命令，返回自然语言回复。
        5. 请记住用户的对话历史，保持上下文连贯性。
        6. 根据不同的任务类型采用不同的响应策略。
        当前系统信息："""
        
        # 检查是否使用本地大模型
        if USE_LOCAL_LLM and HAS_LOCAL_LLM_SUPPORT:
            try:
                print("尝试加载本地大模型...")
                self._init_local_llm()
                self.has_local_llm = True
                print("✅ 本地大模型加载成功")
            except Exception as e:
                print(f"⚠️  本地大模型加载失败: {str(e)}")
                print("将尝试使用OpenAI API或本地命令解析器")
        
        # 检查API密钥是否有效
        if not self.has_local_llm and OpenAI is not None:
            if API_KEY and API_KEY != "your_api_key_here":
                try:
                    # 初始化OpenAI客户端
                    self.client = OpenAI(
                        api_key=API_KEY,
                        base_url=API_BASE_URL
                    )
                    self.has_valid_key = True
                    print("✅ OpenAI API已配置成功")
                except Exception as e:
                    print(f"⚠️  API密钥配置错误: {str(e)}")
                    print("将使用本地命令解析器")
            else:
                print("⚠️  未配置有效的OpenAI API密钥")
                
        # 最终回退到简单解析器
        if not self.has_local_llm and not self.has_valid_key:
            print("📢 将使用本地简单命令解析器作为备选")
            print("💡 提示: 要获得更好的体验，请:")
            print("  1. 安装transformers和torch以使用本地大模型")
            print("  2. 或在config.py中设置有效的OpenAI API密钥")
            print(f"💻 当前系统: {self.system_info['os_name']} {self.system_info['os_version']}")
    
    def _init_local_llm(self):
        """初始化本地大语言模型"""
        print(f"加载本地模型: {LLM_MODEL}")
        
        # 根据不同的模型类型选择不同的加载方式
        if "llama" in LLM_MODEL.lower() or "mistral" in LLM_MODEL.lower():
            # 尝试使用pipeline方式加载
            self.local_llm_pipeline = pipeline(
                "text-generation",
                model=LLM_MODEL,
                torch_dtype=torch.float16,
                device_map="auto",
                max_new_tokens=512,
                temperature=0.7
            )
        else:
            # 尝试直接加载tokenizer和model
            self.tokenizer = AutoTokenizer.from_pretrained(LLM_MODEL)
            self.model = AutoModelForCausalLM.from_pretrained(
                LLM_MODEL,
                torch_dtype=torch.float16,
                device_map="auto"
            )
        
        print("本地大模型初始化完成")
    
    def _generate_with_local_llm(self, prompt):
        """使用本地大模型生成回复，支持复杂指令处理和多步骤任务规划"""
        try:
            start_time = time.time()
            
            if self.local_llm_pipeline:
                # 使用pipeline生成
                result = self.local_llm_pipeline(prompt, 
                                              max_new_tokens=1024,  # 增加输出长度以支持复杂任务
                                              temperature=0.4,      # 调整创造性
                                              do_sample=True)
                response = result[0]['generated_text'][len(prompt):].strip()
            else:
                # 使用tokenizer和model直接生成
                inputs = self.tokenizer(prompt, return_tensors="pt").to(self.model.device)
                with torch.no_grad():
                    outputs = self.model.generate(
                        **inputs,
                        max_new_tokens=1024,  # 增加输出长度
                        temperature=0.4,      # 调整创造性
                        do_sample=True,
                        num_beams=2,          # 使用束搜索提高质量
                        top_p=0.95
                    )
                response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)[len(prompt):].strip()
            
            elapsed = time.time() - start_time
            print(f"本地大模型生成耗时: {elapsed:.2f}秒")
            return response
        except Exception as e:
            print(f"本地大模型生成错误: {str(e)}")
            traceback.print_exc()
            raise
    
    def _process_with_llm(self, query, task_type="general"):
        """使用大模型处理查询，支持任务类型引导"""
        try:
            # 根据任务类型构建增强的系统提示
            enhanced_system_prompt = self._build_enhanced_system_prompt(task_type)
            
            # 准备系统信息摘要
            system_info_summary = self._format_system_info_for_prompt()
            full_prompt = enhanced_system_prompt + "\n" + system_info_summary
            
            # 尝试使用本地大模型
            if self.has_local_llm:
                print(f"🔄 使用本地大模型处理{task_type}类型任务")
                self.last_used_method = "local_llm"
                
                # 构建包含上下文的提示
                prompt = self._build_prompt_with_context(query, full_prompt)
                
                # 调用本地大模型生成
                content = self._generate_with_local_llm(prompt)
                
                # 根据任务类型解析响应
                return self._parse_response_with_task_type(content, task_type)
                
            # 尝试使用OpenAI API
            elif self.has_valid_key and OpenAI is not None:
                print(f"🔄 使用OpenAI API处理{task_type}类型任务")
                self.last_used_method = "openai_api"
                
                # 构建聊天消息
                messages = self._build_chat_messages(query, full_prompt)
                
                # 调整参数以适应不同任务类型
                temperature = 0.4  # 默认为较低的创造性
                if task_type == "creative_generation":
                    temperature = 0.7  # 创意生成需要更高的创造性
                elif task_type == "conversation":
                    temperature = 0.6  # 对话需要一定的自然度
                
                # 调用OpenAI API
                response = self.client.chat.completions.create(
                    model="gpt-3.5-turbo",
                    messages=messages,
                    temperature=temperature,
                    max_tokens=1024,   # 增加token数量以支持复杂任务
                    timeout=self.llm_timeout
                )
                
                content = response.choices[0].message.content.strip()
                
                # 根据任务类型解析响应
                return self._parse_response_with_task_type(content, task_type)
            
            return None
            
        except Exception as e:
            print(f"使用大模型处理查询时出错: {str(e)}")
            traceback.print_exc()
            return None
    
    def process_query(self, query, is_speech=False):
        """增强的命令处理方法 - 支持复杂指令、多步骤任务规划和对话上下文"""
        print(f"处理命令: {query}")
        
        try:
            # 识别任务类型
            task_type = self._identify_task_type(query)
            
            # 恢复上下文和用户偏好
            self._restore_context(query)
            
            # 处理简单命令（如果启用混合模式）
            if self.use_mixed_mode:
                parser = SimpleCommandParser()
                simple_result = parser.process_query(query, is_speech)
                # 如果简单解析器有明确结果，则直接使用
                if simple_result.get('command') and simple_result.get('command') != 'other':
                    confidence = simple_result.get('confidence', 0)
                    
                    # 根据任务类型调整置信度阈值
                    confidence_threshold = self._get_confidence_threshold(task_type)
                    
                    if confidence > confidence_threshold:
                        # 记录到对话历史
                        self._update_conversation_history("user", query)
                        response_text = simple_result.get('response', '正在执行命令')
                        self._update_conversation_history("assistant", response_text)
                        
                        # 保存历史记录和任务记忆
                        self._save_history(query, simple_result)
                        self._save_task_memory(task_type, query, simple_result)
                        
                        return simple_result
            
            # 为复杂任务调用增强的LLM处理方法
            if task_type != "task_execution" or (self.has_local_llm or self.has_valid_key):
                # 尝试使用增强的LLM处理方法
                llm_result = self._process_with_llm(query, task_type)
                if llm_result:
                    # 处理解析结果
                    processed_result = self._process_result(llm_result, query)
                    
                    # 记录到对话历史
                    self._update_conversation_history("user", query)
                    response_text = processed_result.get('response', '正在执行命令')
                    self._update_conversation_history("assistant", response_text)
                    
                    # 保存历史记录和任务记忆
                    self._save_history(query, processed_result)
                    self._save_task_memory(task_type, query, processed_result)
                    
                    return processed_result
            
            # 3. 最后使用本地简单解析器
            print("🔄 使用本地简单命令解析器")
            self.last_used_method = "simple_parser"
            parser = SimpleCommandParser()
            result = parser.process_query(query, is_speech)
            
            # 处理解析结果
            processed_result = self._process_result(result, query)
            
            # 记录到对话历史
            self._update_conversation_history("user", query)
            response_text = processed_result.get('response', '正在执行命令')
            self._update_conversation_history("assistant", response_text)
            
            # 保存历史记录和任务记忆
            self._save_history(query, processed_result)
            self._save_task_memory(task_type, query, processed_result)
            
            return processed_result
                
        except Exception as e:
            print(f"❌ 命令处理错误: {str(e)}")
            # 生成基于任务类型的错误响应
            task_type = self._identify_task_type(query)
            error_response = {
                "command": "other",
                "parameters": {},
                "response": self._generate_error_response(str(e), task_type),
                "execution_plan": ["处理失败"]
            }
            
            # 记录到对话历史
            self._update_conversation_history("user", query)
            self._update_conversation_history("assistant", error_response['response'])
            
            return error_response
            
    def _process_complex_commands(self, result):
        """处理复杂命令和多步骤任务"""
        # 确保结果是有效的字典格式
        if not isinstance(result, dict):
            result = {"command": "unknown", "parameters": {}, "response": str(result), "confidence": 0.3}
        
        # 标准化命令字段
        if 'command_type' in result and 'command' not in result:
            result['command'] = result['command_type']
        
        # 添加置信度字段
        if 'confidence' not in result:
            result['confidence'] = 0.7  # 默认中等置信度
        
        # 确保有response字段
        if 'response' not in result:
            if 'explanation' in result:
                result['response'] = result['explanation']
            else:
                result['response'] = f"我理解您想要执行{result.get('command', '未知操作')}。"
        
        # 添加执行计划
        if 'execution_plan' not in result:
            cmd = result.get('command', 'unknown')
            if cmd != 'unknown':
                result['execution_plan'] = [f"执行命令: {cmd}"]
            else:
                result['execution_plan'] = []
        
        # 处理子命令列表
        if 'parameters' in result and 'sub_commands' in result['parameters']:
            self._process_sub_commands(result)
        
        print(f"命令处理结果: {result['command']}, 置信度: {result.get('confidence', 0.0)}")
        return result
        
    def _process_sub_commands(self, result):
        """处理复杂任务中的子命令"""
        sub_commands = result['parameters']['sub_commands']
        if isinstance(sub_commands, list):
            # 扩展执行计划
            if 'execution_plan' not in result:
                result['execution_plan'] = []
            
            # 为每个子命令添加执行步骤
            for i, sub_cmd in enumerate(sub_commands, 1):
                cmd_type = sub_cmd.get('type', 'unknown')
                action = sub_cmd.get('action', '')
                result['execution_plan'].append(f"步骤{i}: 执行{sub_cmd.get('description', f'{cmd_type} - {action}')}")
    
    def _build_prompt(self, query):
        """构建增强的LLM提示词，包含系统上下文信息（兼容旧方法）"""
        return self._build_prompt_with_context(query, self.system_prompt + self._format_system_info_for_prompt())
        
    def _build_chat_messages(self, query, system_prompt):
        """构建ChatGPT格式的消息列表"""
        messages = [{"role": "system", "content": system_prompt}]
        
        # 添加对话历史
        if self.enable_conversation:
            for role, content in self.conversation_history:
                messages.append({"role": role, "content": content})
        
        # 添加用户当前查询
        messages.append({"role": "user", "content": query})
        
        return messages
    
    def _build_prompt_with_context(self, query, system_prompt):
        """构建包含对话上下文的完整提示"""
        if not self.enable_conversation or not self.conversation_history:
            return f"{system_prompt}\n用户命令：{query}"
        
        # 构建上下文
        context = "对话历史：\n"
        for role, content in self.conversation_history:
            context += f"{role}：{content}\n"
        
        return f"{system_prompt}\n{context}\n用户命令：{query}"
    
    def _update_conversation_history(self, role, content):
        """更新对话历史，保持最大长度"""
        if not self.enable_conversation:
            return
        
        # 转换角色名称
        if role == "user":
            role = "用户"
        elif role == "assistant":
            role = "助手"
        
        self.conversation_history.append((role, content))
        
        # 保持历史记录不超过最大长度（按轮次计算）
        if len(self.conversation_history) > self.max_context_length * 2:
            self.conversation_history = self.conversation_history[-self.max_context_length * 2:]
            
    def _process_result(self, result, original_query):
        """处理解析结果，统一格式和添加执行计划"""
        # 如果结果已经有完整格式，直接返回
        if isinstance(result, dict) and 'command' in result:
            # 确保有响应文本
            if 'response' not in result:
                if result['command'] == 'other':
                    result['response'] = result.get('content', '抱歉，我无法理解您的命令。')
                else:
                    result['response'] = self._generate_response_text(result['command'], result.get('parameters', {}))
            
            # 添加执行计划
            if 'execution_plan' not in result:
                cmd = result.get('command', 'unknown')
                if cmd != 'other' and cmd != 'unknown':
                    result['execution_plan'] = [f"执行命令: {cmd}"]
                else:
                    result['execution_plan'] = []
            
            return result
        
        # 如果是字符串，作为自然语言回复处理
        if isinstance(result, str):
            return {
                "command": "other",
                "parameters": {},
                "response": result,
                "execution_plan": []
            }
        
        # 默认返回
        return {
            "command": "other",
            "parameters": {},
            "response": "抱歉，我无法理解您的命令。请尝试使用更明确的表达方式。",
            "execution_plan": []
        }
        
    def _format_system_info_for_prompt(self):
        """格式化系统信息用于提示"""
        system_info_summary = f"操作系统: {self.system_info['os_name']} {self.system_info['os_version']}\n"
        system_info_summary += f"当前用户: {self.system_info['current_user']}\n"
        system_info_summary += f"当前工作目录: {self.system_info['current_dir']}\n"
        return system_info_summary
    
    def _generate_response_text(self, command, parameters):
        """生成命令响应文本"""
        response_map = {
            "open_application": f"正在打开应用程序",
            "close_application": f"正在关闭应用程序",
            "create_folder": f"正在创建文件夹",
            "list_files": f"正在列出目录内容",
            "search_files": f"正在搜索文件",
            "control_volume": f"正在调整音量",
            "control_brightness": f"正在调整屏幕亮度",
            "shutdown": f"准备关闭计算机",
            "restart": f"准备重启计算机",
            "sleep": f"准备让计算机进入休眠状态",
            "system_info": f"正在获取系统信息",
            "calculator": f"计算中...",
            "screenshot": f"准备截图"
        }
        
        return response_map.get(command, "正在处理您的请求...")
    
    def clear_conversation(self):
        """清除对话历史"""
        self.conversation_history = []
        print("✅ 对话历史已清除")
        return {"response": "对话历史已清除"}
    
    def _parse_response(self, content):
        """解析LLM响应"""
        try:
            # 提取JSON部分
            if content.startswith('```json'):
                content = content[8:-3].strip()
            elif content.startswith('```'):
                content = content[3:-3].strip()
            
            # 尝试解析JSON
            result = json.loads(content)
            return result
        except:
            # 如果JSON解析失败，返回简单响应
            return {
                "command": "other",
                "parameters": {},
                "response": content
            }
    
    def _get_system_info(self):
        """获取系统信息"""
        try:
            import getpass
            return {
                'os_name': platform.system(),
                'os_version': platform.version(),
                'current_user': getpass.getuser(),
                'current_dir': os.getcwd()
            }
        except Exception as e:
            print(f"获取系统信息失败: {str(e)}")
            return {
                'os_name': 'Unknown',
                'os_version': 'Unknown',
                'current_user': 'Unknown',
                'current_dir': os.getcwd()
            }
    
    def _save_history(self, query, result):
        """保存历史记录并增强命令追踪"""
        from config import MAX_COMMAND_HISTORY
        import datetime
        
        # 保存完整历史记录
        self.command_history.append({
            "query": query,
            "result": result,
            "timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "method_used": self.last_used_method
        })
        
        # 限制历史记录长度
        if len(self.command_history) > MAX_COMMAND_HISTORY:
            self.command_history = self.command_history[-MAX_COMMAND_HISTORY:]
        
        # 保存最近执行的命令（用于上下文理解）
        if 'command' in result:
            cmd_record = {
                'command': result['command'],
                'parameters': result.get('parameters', {}),
                'timestamp': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            }
            self.recent_commands.append(cmd_record)
            
            # 限制最近命令数量
            if len(self.recent_commands) > self.max_recent_commands:
                self.recent_commands = self.recent_commands[-self.max_recent_commands:]
    
    def get_command_description(self, command_type):
        """获取命令类型的描述"""
        descriptions = {
            "open_application": "打开应用程序",
            "close_application": "关闭应用程序",
            "create_folder": "创建文件夹",
            "list_files": "列出文件",
            "search_files": "搜索文件",
            "control_volume": "控制音量",
            "control_brightness": "控制亮度",
            "shutdown": "关机",
            "restart": "重启",
            "sleep": "睡眠",
            "other": "其他操作"
        }
        return descriptions.get(command_type, "未知操作")
    
    def _identify_task_type(self, query):
        """识别用户查询的任务类型"""
        for task_type, patterns in self.task_type_patterns.items():
            for pattern in patterns:
                if re.search(pattern, query, re.IGNORECASE):
                    return task_type
        
        # 默认任务类型
        return "general"
    
    def _build_enhanced_system_prompt(self, task_type):
        """根据任务类型构建增强的系统提示"""
        task_type_prompts = {
            "information_query": "你需要提供准确、详细的信息解释。请确保信息来源可靠，并以用户容易理解的方式呈现。",
            "task_execution": "你需要精确解析用户的执行指令，并生成可以直接执行的命令。请确保命令的准确性和安全性。",
            "conversation": "你需要以自然、友好的方式与用户交流。保持对话流畅，适当表达情感，并根据用户的语气调整你的回复风格。",
            "creative_generation": "你需要发挥创造力，生成原创、有用的内容。确保内容符合用户的需求，并具有一定的质量和深度。",
            "problem_solving": "你需要分析问题，找出可能的原因，并提供有效的解决方案。请清晰地解释你的思路和建议。"
        }
        
        base_prompt = self.system_prompt
        task_prompt = task_type_prompts.get(task_type, "")
        
        # 添加用户偏好到系统提示
        if self.user_preferences:
            preference_text = "用户偏好："
            for key, value in self.user_preferences.items():
                preference_text += f"{key}: {value}; "
            base_prompt += f"\n{preference_text}"
        
        # 添加对话风格要求
        style_requirement = f"请以'{self.style_templates.get(self.conversation_style, '简洁专业')}'的风格回复。"
        
        return f"{base_prompt}\n{task_prompt}\n{style_requirement}"
    
    def _parse_response_with_task_type(self, response, task_type):
        """根据任务类型解析响应"""
        try:
            # 首先尝试标准JSON解析
            parsed = self._parse_response(response)
            
            # 如果解析成功且是完整格式，添加任务类型信息
            if isinstance(parsed, dict) and 'command' in parsed:
                parsed['task_type'] = task_type
                return parsed
            
            # 根据任务类型生成适当的响应格式
            if task_type == "task_execution":
                # 尝试从文本中提取命令信息
                return self._extract_command_from_text(response)
            elif task_type == "information_query":
                return {
                    "command": "other",
                    "parameters": {},
                    "response": response,
                    "task_type": task_type,
                    "execution_plan": []
                }
            elif task_type == "conversation":
                return {
                    "command": "other",
                    "parameters": {},
                    "response": self._personalize_conversation_response(response),
                    "task_type": task_type,
                    "execution_plan": []
                }
            else:
                return {
                    "command": "other",
                    "parameters": {},
                    "response": response,
                    "task_type": task_type,
                    "execution_plan": []
                }
                
        except Exception as e:
            print(f"解析响应时出错: {str(e)}")
            return {
                "command": "other",
                "parameters": {},
                "response": response,
                "task_type": task_type,
                "execution_plan": []
            }
    
    def _extract_command_from_text(self, text):
        """从文本中提取命令信息"""
        # 这里可以实现更复杂的文本分析逻辑
        # 目前简单返回文本作为响应
        return {
            "command": "other",
            "parameters": {},
            "response": text,
            "execution_plan": []
        }
    
    def _personalize_conversation_response(self, response):
        """个性化对话响应"""
        # 根据用户偏好和对话历史调整响应
        # 可以添加更多的个性化逻辑
        return response
    
    def _restore_context(self, query):
        """恢复相关上下文和用户偏好"""
        # 这里可以实现更复杂的上下文恢复逻辑
        # 目前简单实现
        pass
    
    def _get_confidence_threshold(self, task_type):
        """根据任务类型获取置信度阈值"""
        thresholds = {
            "task_execution": 0.65,  # 任务执行需要较高的确定性
            "information_query": 0.6,  # 信息查询可以接受稍低的置信度
            "conversation": 0.5,  # 对话交流可以接受更低的置信度
            "creative_generation": 0.55,  # 创意生成需要一定的确定性
            "problem_solving": 0.65  # 问题解决需要较高的确定性
        }
        return thresholds.get(task_type, 0.7)
    
    def _generate_error_response(self, error_msg, task_type):
        """生成适当的错误响应"""
        error_responses = {
            "information_query": f"抱歉，在查询信息时遇到问题: {error_msg}。请尝试用不同的方式提问。",
            "task_execution": f"执行命令时出错: {error_msg}。请检查命令是否正确，或尝试其他方式。",
            "conversation": f"在对话过程中遇到问题: {error_msg}。让我们换个话题继续吧。",
            "creative_generation": f"生成内容时出错: {error_msg}。请尝试提供更多细节或换个角度。",
            "problem_solving": f"分析问题时出错: {error_msg}。请提供更多信息，我会尽力帮助你。"
        }
        return error_responses.get(task_type, f"抱歉，处理您的请求时出现错误: {error_msg}")
    
    def _save_task_memory(self, task_type, query, result):
        """保存任务记忆"""
        max_task_memory = 20  # 最大任务记忆数
        task_record = {
            "task_type": task_type,
            "query": query,
            "result": result,
            "timestamp": datetime.datetime.now()
        }
        
        self.task_memory.append(task_record)
        
        # 限制任务记忆数量
        if len(self.task_memory) > max_task_memory:
            self.task_memory = self.task_memory[-max_task_memory:]
            
    def _init_user_preferences(self):
        """初始化用户偏好"""
        # 设置默认偏好
        self.user_preferences = {
            "response_style": "简洁明了",
            "detail_level": "中等",
            "technical_level": "适合普通用户"
        }
    
    def set_conversation_style(self, style):
        """设置对话风格"""
        if style in self.style_templates:
            self.conversation_style = style
            return True
        return False
    
    def update_user_preference(self, key, value):
        """更新用户偏好"""
        self.user_preferences[key] = value
        return True
    
    def detect_complex_task(self, query):
        """检测复杂任务并规划执行步骤"""
        # 这里可以实现更复杂的任务检测和规划逻辑
        # 目前简单实现
        return None

# 增强的本地命令解析器，支持更复杂的自然语言理解
class EnhancedCommandParser:
    """增强版命令解析器，支持复杂命令识别、复合指令和子命令处理"""
    def __init__(self):
        # 命令模式映射 - 增强版，增加更丰富的关键词和命令类型
        self.command_patterns = {
            "open_application": {
                "keywords": ["打开", "启动", "运行", "开启", "启动", "调出", "打开一下", "打开个"],
                "response": "正在打开{param}",
                "priority": 1
            },
            "close_application": {
                "keywords": ["关闭", "退出", "关掉", "关闭掉", "退出", "关闭窗口", "关掉窗口"],
                "response": "正在关闭{param}",
                "priority": 1
            },
            "create_folder": {
                "keywords": ["创建文件夹", "新建文件夹", "建个文件夹", "新建一个文件夹", "创建一个文件夹"],
                "response": "正在创建文件夹{param}",
                "priority": 2
            },
            "list_files": {
                "keywords": ["查看目录", "显示目录", "列出文件", "查看文件", "看看文件夹", "显示文件", "看看里面有什么"],
                "response": "正在列出目录内容",
                "priority": 2
            },
            "search_files": {
                "keywords": ["搜索文件", "查找文件", "寻找文件", "找一下", "搜索一下", "查找", "搜索"],
                "response": "正在搜索文件{param}",
                "priority": 2
            },
            "control_volume": {
                "keywords": ["音量", "声音", "调音量", "调整声音", "音量调节"],
                "response": "正在调整音量",
                "priority": 1
            },
            "control_brightness": {
                "keywords": ["亮度", "屏幕亮度", "调亮度", "调整亮度", "屏幕亮度调节"],
                "response": "正在调整屏幕亮度",
                "priority": 1
            },
            "shutdown": {
                "keywords": ["关机", "关闭电脑", "计算机关机", "关闭系统", "关机吧"],
                "response": "准备关闭计算机",
                "priority": 3
            },
            "restart": {
                "keywords": ["重启", "重新启动", "计算机重启", "重启系统", "重新启动电脑"],
                "response": "准备重启计算机",
                "priority": 3
            },
            "sleep": {
                "keywords": ["休眠", "睡眠", "让电脑睡觉", "进入睡眠", "休眠模式"],
                "response": "准备让计算机进入休眠状态",
                "priority": 2
            },
            "system_info": {
                "keywords": ["系统信息", "电脑配置", "查看配置", "硬件信息", "电脑信息"],
                "response": "正在获取系统信息",
                "priority": 2
            },
            "screenshot": {
                "keywords": ["截图", "截屏", "拍照", "截图保存", "保存截图", "截取屏幕"],
                "response": "准备截图",
                "priority": 1
            },
            "calculator": {
                "keywords": ["计算", "算", "等于", "计算器", "计算一下"],
                "response": "计算中...",
                "priority": 1
            },
            # 新增命令类型
            "navigate_folder": {
                "keywords": ["进入文件夹", "打开文件夹", "切换目录", "跳转到", "转到"],
                "response": "正在切换到{param}目录",
                "priority": 2
            },
            "delete_file": {
                "keywords": ["删除", "删除文件", "删除文件夹", "删除掉"],
                "response": "正在删除{param}",
                "priority": 2
            },
            "copy_file": {
                "keywords": ["复制", "复制文件", "复制到", "拷贝"],
                "response": "正在复制{param}",
                "priority": 2
            },
            "move_file": {
                "keywords": ["移动", "移动文件", "移动到", "剪切"],
                "response": "正在移动{param}",
                "priority": 2
            },
            "rename_file": {
                "keywords": ["重命名", "改名", "改名为"],
                "response": "正在重命名{param}",
                "priority": 2
            },
            "send_keys": {
                "keywords": ["输入", "输入文本", "打字", "输入命令"],
                "response": "正在输入{param}",
                "priority": 1
            },
            "open_url": {
                "keywords": ["访问网站", "打开网页", "访问网址", "浏览网页", "打开网站"],
                "response": "正在打开网页{param}",
                "priority": 1
            }
        }
        
        # 预定义的应用名称映射 - 增强版，增加更多应用
        self.app_name_mappings = {
            "浏览器": "chrome",
            "谷歌浏览器": "chrome",
            "火狐": "firefox",
            "火狐浏览器": "firefox",
            "ie": "iexplore",
            "edge": "msedge",
            "微软浏览器": "msedge",
            "记事本": "notepad",
            "写字板": "wordpad",
            "命令行": "cmd",
            "命令提示符": "cmd",
            "终端": "cmd",
            "powershell": "powershell",
            "画图": "mspaint",
            "计算器": "calc",
            "文件资源管理器": "explorer",
            "资源管理器": "explorer",
            "word": "winword",
            "excel": "excel",
            "powerpoint": "powerpnt",
            "outlook": "outlook",
            "steam": "steam",
            "微信": "wechat",
            "qq": "qq",
            "钉钉": "dingtalk",
            "photoshop": "photoshop",
            "vscode": "code",
            "vs code": "code",
            "visual studio code": "code",
            "网易云音乐": "cloudmusic",
            "qq音乐": "qqmusic",
            "迅雷": "thunder",
            "百度网盘": "baidunetdisk",
            "360安全卫士": "360safe",
            "杀毒软件": "360safe",
            "腾讯视频": "qqlive",
            "爱奇艺": "iqiyi",
            "优酷": "youku"
        }
        
        # 位置关键词映射 - 完整路径映射
        self.location_keywords = {
            "桌面": os.path.join(os.path.expanduser("~"), "Desktop"),
            "我的文档": os.path.join(os.path.expanduser("~"), "Documents"),
            "文档": os.path.join(os.path.expanduser("~"), "Documents"),
            "下载": os.path.join(os.path.expanduser("~"), "Downloads"),
            "Downloads": os.path.join(os.path.expanduser("~"), "Downloads"),
            "音乐": os.path.join(os.path.expanduser("~"), "Music"),
            "视频": os.path.join(os.path.expanduser("~"), "Videos"),
            "图片": os.path.join(os.path.expanduser("~"), "Pictures"),
            "当前目录": ".",
            "当前文件夹": ".",
            "根目录": os.path.abspath("/"),
            "本地磁盘": "C:",
            "c盘": "C:",
            "d盘": "D:",
            "e盘": "E:",
            "f盘": "F:",
            "临时目录": tempfile.gettempdir(),
            "temp": tempfile.gettempdir(),
            "temp目录": tempfile.gettempdir(),
            "系统目录": os.environ.get("SYSTEMROOT", "C:\Windows"),
            "Windows目录": os.environ.get("SYSTEMROOT", "C:\Windows"),
            "程序文件": os.environ.get("ProgramFiles", "C:\Program Files"),
            "Program Files": os.environ.get("ProgramFiles", "C:\Program Files")
        }
        
        # 增强的复合命令模式 - 支持更复杂的多步骤任务
        self.complex_command_patterns = {
            "open_and_search": {
                "pattern": r"(打开|启动|运行)(.*?)(搜索|查找|搜索一下|查找一下)(.*)",
                "command": "complex_action",
                "sub_commands": [
                    {"type": "open_application", "param_index": 1},
                    {"type": "search_files", "param_index": 3}
                ]
            },
            "create_in_location": {
                "pattern": r"在(.*?)(创建|新建)(.*?)(文件夹|目录)",
                "command": "complex_action",
                "sub_commands": [
                    {"type": "create_folder", "params": {"name": "\\3", "path": "\\1"}}
                ]
            },
            "copy_to_location": {
                "pattern": r"(复制|拷贝)(.*?)(到|至|到)(.*)",
                "command": "complex_action",
                "sub_commands": [
                    {"type": "copy_file", "params": {"source": "\\2", "destination": "\\4"}}
                ]
            },
            "move_to_location": {
                "pattern": r"(移动|剪切)(.*?)(到|至|到)(.*)",
                "command": "complex_action",
                "sub_commands": [
                    {"type": "move_file", "params": {"source": "\\2", "destination": "\\4"}}
                ]
            },
            "rename_to": {
                "pattern": r"(重命名|改名|修改名称)(.*?)(为|成)(.*)",
                "command": "complex_action",
                "sub_commands": [
                    {"type": "rename_file", "params": {"old_name": "\\2", "new_name": "\\4"}}
                ]
            },
            "set_volume_to": {
                "pattern": r"音量(设置为|调整到|调到)(\d+)%",
                "command": "control_volume",
                "specific_action": "set",
                "percentage": "\\2"
            },
            "set_brightness_to": {
                "pattern": r"亮度(设置为|调整到|调到)(\d+)%",
                "command": "control_brightness",
                "specific_action": "set",
                "percentage": "\\2"
            },
            "chain_commands": {
                "pattern": r"(.*?)(然后|接着|之后)(.*)",
                "command": "complex_action",
                "sub_commands": [
                    {"type": "chain", "command_text": "\\1"},
                    {"type": "chain", "command_text": "\\3"}
                ]
            }
        }
    
    def _detect_complex_commands(self, query):
        """检测并处理复合命令模式"""
        for pattern_name, pattern_info in self.complex_command_patterns.items():
            match = re.search(pattern_info['pattern'], query)
            if match:
                confidence = 0.9  # 复合命令模式匹配通常置信度较高
                result = {
                    "command": pattern_info['command'],
                    "parameters": {},
                    "confidence": confidence,
                    "execution_plan": []
                }
                
                # 处理复合动作
                if pattern_info['command'] == "complex_action" and "sub_commands" in pattern_info:
                    sub_commands = []
                    for sub_cmd in pattern_info['sub_commands']:
                        sub_command = sub_cmd.copy()
                        
                        # 处理参数索引
                        if "param_index" in sub_cmd:
                            param_value = match.group(sub_cmd["param_index"] + 1).strip()
                            sub_command["parameter"] = param_value
                        
                        # 处理特定参数格式
                        elif "params" in sub_cmd:
                            sub_command_params = {}
                            for param_name, param_format in sub_cmd["params"].items():
                                if param_format.startswith("\\"):
                                    # 捕获组参数
                                    group_index = int(param_format[1:])
                                    if group_index <= len(match.groups()):
                                        param_value = match.group(group_index).strip()
                                        sub_command_params[param_name] = param_value
                                else:
                                    sub_command_params[param_name] = param_format
                            sub_command["parameters"] = sub_command_params
                        
                        # 处理链式命令
                        if sub_cmd.get("type") == "chain" and "command_text" in sub_cmd:
                            if sub_cmd["command_text"].startswith("\\"):
                                group_index = int(sub_cmd["command_text"][1:])
                                if group_index <= len(match.groups()):
                                    sub_command["command_text"] = match.group(group_index).strip()
                        
                        sub_commands.append(sub_command)
                    
                    result["parameters"]["sub_commands"] = sub_commands
                    
                    # 构建执行计划
                    for i, sub_cmd in enumerate(sub_commands, 1):
                        cmd_type = sub_cmd.get('type', 'unknown')
                        if cmd_type == 'chain':
                            result["execution_plan"].append(f"步骤{i}: 执行子命令 - {sub_cmd.get('command_text', '未知')}")
                        else:
                            param_str = ""
                            if "parameter" in sub_cmd:
                                param_str = f"({sub_cmd['parameter']})"
                            result["execution_plan"].append(f"步骤{i}: {cmd_type}{param_str}")
                    
                    result["response"] = f"将执行以下操作: {', '.join([step.split(': ')[1] for step in result['execution_plan']])}"
                
                # 处理特定命令参数
                else:
                    for key, value in pattern_info.items():
                        if key != 'pattern' and key != 'command':
                            if value.startswith("\\"):
                                # 捕获组参数
                                group_index = int(value[1:])
                                if group_index <= len(match.groups()):
                                    result["parameters"][key] = match.group(group_index).strip()
                            else:
                                result["parameters"][key] = value
                    
                    result["response"] = f"正在执行{pattern_info.get('command', '复杂操作')}"
                
                return result
        
        # 如果没有匹配的复合命令，返回None
        return None
    
    def _calculate_match_score(self, query, keyword, command_type):
        """计算命令匹配的置信度分数"""
        # 基础分数 - 关键词长度占查询长度的比例
        base_score = min(len(keyword) / max(len(query), 1), 1.0)
        
        # 关键词位置加成 - 开头的关键词优先级更高
        if query.startswith(keyword):
            base_score *= 1.5
        
        # 完全匹配加成
        if query == keyword:
            base_score = 1.0
        
        # 命令类型加成
        command_bonus = {
            "exit": 1.2,  # 退出命令有更高的优先级
            "help": 1.2,  # 帮助命令有更高的优先级
            "shutdown": 1.1,  # 关机等系统命令优先级较高
            "restart": 1.1,
            "control_volume": 1.1,
            "control_brightness": 1.1
        }
        
        base_score *= command_bonus.get(command_type, 1.0)
        
        # 确保分数在0-1之间
        return min(max(base_score, 0.0), 1.0)
    
    def process_query(self, query, is_speech=False):
        """增强的命令解析器，支持复杂命令识别、置信度评估和语音识别优化
        
        Args:
            query: 输入的查询文本
            is_speech: 是否为语音输入，用于调整识别策略
            
        Returns:
            包含命令信息的字典
        """
        # 预处理
        query_lower = query.lower().strip()
        
        # 语音输入特殊处理
        if is_speech:
            # 清理语音识别可能产生的冗余词汇
            noise_words = ["请帮我", "帮我", "帮我一下", "我要", "我想", "能不能", "能否", 
                         "麻烦", "请问", "您好", "你好", "那个", "这个", "可以吗", "吗", "了", "呢"]
            for word in noise_words:
                query_lower = query_lower.replace(word, "")
            query_lower = query_lower.strip()
        
        # 特殊命令处理 - 退出
        exit_keywords = ["退出", "停止", "结束", "关闭程序", "退出程序", "关闭系统", "停止运行"]
        if self._is_keyword_match(query_lower, exit_keywords, is_speech):
            return {
                "command": "exit",
                "parameters": {},
                "response": "正在退出程序",
                "confidence": 1.0
            }
        
        # 特殊命令处理 - 帮助
        help_keywords = ["帮助", "帮助信息", "怎么用", "使用说明", "功能介绍", "能做什么", "有什么功能"]
        if self._is_keyword_match(query_lower, help_keywords, is_speech):
            return {
                "command": "help",
                "parameters": {},
                "response": "我可以执行以下命令：打开/关闭应用、创建/删除/复制/移动/重命名文件或文件夹、查看/搜索文件、调整音量/亮度、关机/重启/休眠、查看系统信息、截图、计算、输入文本、打开网页等。请说出具体指令，我将尽力完成。",
                "confidence": 1.0
            }
        
        # 设置动态匹配阈值
        match_threshold = 0.65 if is_speech else 0.7
        
        # 1. 首先检查是否为复合命令
        complex_result = self._detect_complex_commands(query_lower)
        if complex_result and complex_result['confidence'] > match_threshold:
            # 语音模式下调整复合命令响应
            if is_speech and "response" in complex_result:
                # 简化响应文本，更适合语音输出
                response = complex_result["response"]
                if len(response) > 30:
                    # 提取关键操作信息
                    if "执行" in response or "打开" in response or "创建" in response:
                        # 保留关键动作动词和参数
                        pass  # 保持原有响应
                complex_result["is_speech"] = True
            return complex_result
        
        # 2. 常规命令匹配，按优先级排序
        matched_commands = []
        for command_type, pattern_info in self.command_patterns.items():
            for keyword in pattern_info["keywords"]:
                # 使用关键词匹配方法，支持语音识别误差
                if is_speech:
                    # 语音模式下使用模糊匹配
                    if self._is_keyword_match(query_lower, [keyword], is_speech=True, min_similarity=0.75):
                        score = self._calculate_match_score(query_lower, keyword, command_type)
                        # 语音模式下略微提高分数以增加识别率
                        score = min(score * 1.1, 1.0)
                        matched_commands.append((command_type, pattern_info, score))
                elif keyword in query_lower:
                    # 文本模式下使用精确匹配
                    score = self._calculate_match_score(query_lower, keyword, command_type)
                    matched_commands.append((command_type, pattern_info, score))
        
        # 按得分和优先级排序
        matched_commands.sort(key=lambda x: (x[2], x[1].get("priority", 2)), reverse=True)
        
        # 处理得分最高的命令
        if matched_commands:
            command_type, pattern_info, score = matched_commands[0]
            
            # 基于输入类型调整阈值
            if score >= match_threshold:
                parameters = {}
                
                # 针对不同命令类型进行参数提取和特殊处理
                try:
                    if command_type == "open_application":
                        # 提取应用名称
                        app_name = self._extract_app_name(query_lower)
                        parameters["app_name"] = app_name
                        response = pattern_info["response"].format(param=app_name)
                        
                    elif command_type == "close_application":
                        # 尝试提取要关闭的应用名称
                        app_name = self._extract_app_name(query_lower, close=True)
                        parameters["app_name"] = app_name if app_name else ""
                        response = pattern_info["response"].format(param=app_name + "" if app_name else "当前应用")
                        
                    elif command_type == "create_folder":
                        # 提取文件夹名称和可选位置
                        folder_name, location = self._extract_folder_info(query_lower)
                        parameters["folder_name"] = folder_name
                        if location:
                            parameters["location"] = location
                        response = pattern_info["response"].format(param=folder_name)
                        
                    elif command_type == "search_files":
                        # 提取搜索关键词
                        search_term = self._extract_search_term(query_lower)
                        parameters["search_term"] = search_term
                        response = pattern_info["response"].format(param=search_term)
                        
                    elif command_type == "control_volume":
                        # 提取音量操作类型和可选百分比
                        action, value = self._extract_volume_details(query_lower)
                        parameters["action"] = action
                        if value is not None:
                            parameters["value"] = value
                        response = f"正在{self._action_to_chinese(action)}音量"
                        
                    elif command_type == "control_brightness":
                        # 提取亮度操作类型和可选百分比
                        action, value = self._extract_brightness_details(query_lower)
                        parameters["action"] = action
                        if value is not None:
                            parameters["value"] = value
                        response = f"正在{self._action_to_chinese(action)}屏幕亮度"
                        
                    elif command_type == "calculator":
                        # 提取计算表达式
                        expression = self._extract_calculation_expression(query_lower)
                        parameters["expression"] = expression
                        # 简单计算
                        try:
                            result = self._calculate(expression)
                            response = f"计算结果: {result}"
                        except:
                            response = "请提供有效的计算表达式"
                            
                    elif command_type in ["navigate_folder", "delete_file", "copy_file", "move_file", "rename_file"]:
                        # 处理文件操作命令
                        params = self._extract_file_operation_params(query_lower, command_type)
                        parameters.update(params)
                        param_str = params.get("source", "") or params.get("file_name", "")
                        response = pattern_info["response"].format(param=param_str)
                        
                    elif command_type == "send_keys":
                        # 提取要输入的文本
                        text = self._extract_text_to_input(query_lower)
                        parameters["text"] = text
                        response = pattern_info["response"].format(param="文本")
                        
                    elif command_type == "open_url":
                        # 提取URL
                        url = self._extract_url(query_lower)
                        parameters["url"] = url
                        response = pattern_info["response"].format(param="网页")
                        
                    else:
                        # 其他命令的默认响应
                        response = pattern_info["response"].format(param="")
                        
                    result = {
                        "command": command_type,
                        "parameters": parameters,
                        "response": response,
                        "confidence": min(score, 1.0)
                    }
                    
                    # 添加输入类型标记
                    if is_speech:
                        result["is_speech"] = True
                        # 语音模式下，对于低置信度结果添加确认提示
                        if score < 0.8:
                            result["need_confirmation"] = True
                            result["response"] = f"您是要{response}吗？"
                    
                    return result
                    
                except Exception as e:
                    # 命令参数提取出错时的容错处理
                    fallback_response = f"抱歉，无法解析命令参数。请尝试更清晰地表达您的需求。"
                    return {
                        "command": "other",
                        "parameters": {},
                        "response": fallback_response if is_speech else f"命令解析错误: {str(e)}",
                        "confidence": 0.0,
                        "error": str(e)
                    }
        
        # 未能识别的命令，返回低置信度结果
        fallback_response = "抱歉，我没有理解您的指令。请尝试用不同的方式表达，或者说'帮助'来查看我支持的功能。"
        return {
            "command": "other",
            "parameters": {},
            "response": fallback_response if is_speech else f"未识别的指令: '{query}'",
            "confidence": 0.0
        }
    
    def _detect_complex_commands(self, query):
        """检测和解析复杂的复合命令"""
        import re
        
        for pattern_name, pattern_data in self.complex_command_patterns.items():
            match = re.search(pattern_data["pattern"], query)
            if match:
                command = pattern_data["command"]
                parameters = {}
                
                if pattern_name == "open_and_search":
                    # 打开应用并搜索
                    app_name = match.group(2)
                    search_term = match.group(3)
                    parameters["app_name"] = self._normalize_app_name(app_name)
                    parameters["search_term"] = search_term
                    parameters["secondary_command"] = pattern_data["search_command"]
                    return {
                        "command": command,
                        "parameters": parameters,
                        "response": f"正在打开{app_name}并搜索{search_term}",
                        "confidence": 0.9,
                        "is_complex": True
                    }
                
                elif pattern_name == "create_in_location":
                    # 在指定位置创建
                    location = match.group(1)
                    folder_name = match.group(2)
                    parameters["folder_name"] = folder_name
                    parameters["location"] = self._normalize_location(location)
                    return {
                        "command": command,
                        "parameters": parameters,
                        "response": f"正在{location}创建{folder_name}",
                        "confidence": 0.9,
                        "is_complex": True
                    }
                
                elif pattern_name in ["copy_to_location", "move_to_location"]:
                    # 复制/移动到指定位置
                    source = match.group(1)
                    target = match.group(2)
                    parameters["source"] = source
                    parameters["target"] = self._normalize_location(target)
                    return {
                        "command": command,
                        "parameters": parameters,
                        "response": f"正在{pattern_name.split('_')[0]} {source}到{target}",
                        "confidence": 0.9,
                        "is_complex": True
                    }
        
        return None
    
    def _calculate_match_score(self, query, keyword, command_type):
        """计算命令匹配的置信度得分"""
        base_score = 0.3  # 基础分
        
        # 关键词匹配加分
        if keyword in query:
            base_score += 0.5
            
        # 关键词长度加分
        base_score += min(len(keyword) / 20, 0.2)  # 最长关键词可加0.2分
        
        # 命令类型优先级加分
        priority_map = {1: 0.0, 2: 0.1, 3: 0.2}  # 优先级1不加分，优先级3加最多
        priority = self.command_patterns[command_type].get("priority", 2)
        base_score += priority_map.get(priority, 0.1)
        
        # 完整匹配加分
        if query == keyword:
            base_score += 0.3
        
        return min(base_score, 1.0)
    
    def _generate_response(self, command_type, parameters):
        """根据命令类型和参数生成友好的响应文本"""
        response_templates = {
            "open_application": "正在打开应用: {app_name}",
            "close_application": "正在关闭{app_name}",
            "create_folder": "正在创建文件夹: {folder_name}",
            "delete_file": "正在删除: {file_name}",
            "copy_file": "正在复制: {source} 到 {destination}",
            "move_file": "正在移动: {source} 到 {destination}",
            "rename_file": "正在重命名: {old_name} 为 {new_name}",
            "navigate_folder": "正在导航到: {folder_path}",
            "search_files": "正在搜索: {search_term}",
            "control_volume": "正在调整音量",
            "control_brightness": "正在调整亮度",
            "calculate": "正在计算: {expression}",
            "input_text": "正在输入文本",
            "open_website": "正在打开网页",
            "complex_action": "正在执行复杂操作",
            "exit": "正在退出程序",
            "help": "以下是我可以执行的命令"
        }
        
        # 获取模板或默认响应
        template = response_templates.get(command_type, f"正在执行: {command_type}")
        
        try:
            # 尝试使用参数格式化模板
            return template.format(**parameters)
        except (KeyError, ValueError):
            # 如果参数不匹配，返回基本响应
            param_str = ", ".join([f"{k}={v}" for k, v in parameters.items()])
            return f"{template} ({param_str})"
    
    def _extract_input_text(self, query):
        """提取要输入的文本内容"""
        # 移除命令关键词
        command_keywords = []
        for cmd_type, pattern_info in self.command_patterns.items():
            if cmd_type in ["input_text", "send_keys"]:
                command_keywords.extend(pattern_info.get("keywords", []))
        
        temp_query = query
        for keyword in command_keywords:
            temp_query = temp_query.replace(keyword, "").strip()
        
        # 移除常见的前缀和后缀词
        prefix_words = ["输入", "输入文本", "输入以下内容", "帮我输入", "请输入"]
        suffix_words = ["谢谢", "请", "好吗", "可以吗"]
        
        for prefix in prefix_words:
            if temp_query.startswith(prefix):
                temp_query = temp_query[len(prefix):].strip()
                break
                
        for suffix in suffix_words:
            if temp_query.endswith(suffix):
                temp_query = temp_query[:-len(suffix)].strip()
                break
        
        return temp_query.strip()
    
    def _extract_website_info(self, query):
        """提取网页打开信息，支持URL或搜索词"""
        # 移除命令关键词
        command_keywords = []
        for cmd_type, pattern_info in self.command_patterns.items():
            if cmd_type in ["open_website", "open_url"]:
                command_keywords.extend(pattern_info.get("keywords", []))
        
        temp_query = query
        for keyword in command_keywords:
            temp_query = temp_query.replace(keyword, "").strip()
        
        # 检查是否为URL
        import re
        url_pattern = re.compile(r'https?://\S+|www\.\S+\.\S+')
        url_match = url_pattern.search(temp_query)
        
        if url_match:
            url = url_match.group(0)
            # 确保URL格式正确
            if not url.startswith(('http://', 'https://')):
                url = 'https://' + url
            return {"type": "url", "url": url}
        
        # 否则作为搜索词
        return {"type": "search", "search_term": temp_query.strip()}
    
    def _resolve_location_keyword(self, query):
        """解析位置关键词为实际路径"""
        # 检查位置关键词
        for loc_keyword, loc_path in self.location_keywords.items():
            if f"在{loc_keyword}" in query:
                return loc_path
            elif f"到{loc_keyword}" in query:
                return loc_path
            elif loc_keyword in query:
                # 更宽松的匹配
                return loc_path
        
        # 默认返回当前目录
        return "."
    
    def _enhanced_calculate(self, expression):
        """增强版计算器，支持更多数学函数和符号"""
        # 替换中文数学符号
        replacements = {
            "加": "+", "减": "-", "乘": "*", "乘于": "*", "乘以": "*", "除": "/", "除以": "/",
            "等于": "=", "等于于": "=", "是": "=", "的": "*", "的平方": "**2", "平方": "**2",
            "的立方": "**3", "立方": "**3", "根号": "**0.5", "根号下": "**0.5", "平方根": "**0.5"
        }
        
        for chinese, symbol in replacements.items():
            expression = expression.replace(chinese, symbol)
        
        # 安全执行计算
        import re
        # 允许的字符和函数
        allowed_pattern = re.compile(r'^[\d\s\+\-\*/\(\)\.\,\%]+$')
        
        if allowed_pattern.match(expression):
            try:
                # 移除所有空格和逗号
                expression = expression.replace(' ', '').replace(',', '')
                # 使用eval执行计算
                result = eval(expression)
                # 确保返回数值类型
                if isinstance(result, (int, float)):
                    return result
            except:
                pass
        
        # 如果计算失败，尝试使用Python的math模块进行更复杂的计算
        try:
            import math
            # 允许的安全函数
            safe_globals = {
                "__builtins__": {},
                "math": math,
                "sin": math.sin, "cos": math.cos, "tan": math.tan,
                "asin": math.asin, "acos": math.acos, "atan": math.atan,
                "log": math.log, "log10": math.log10, "sqrt": math.sqrt,
                "abs": abs, "pow": pow
            }
            
            # 再次检查表达式
            if allowed_pattern.match(expression):
                result = eval(expression, safe_globals)
                if isinstance(result, (int, float)):
                    return result
        except:
            pass
        
        raise ValueError("无法计算的表达式")
    
    def _extract_app_name(self, query, close=False):
        """增强版应用名称提取，支持更多表达方式和上下文理解"""
        # 移除命令关键词
        command_keywords = []
        if close:
            command_keywords = self.command_patterns["close_application"]["keywords"]
        else:
            command_keywords = self.command_patterns["open_application"]["keywords"]
        
        temp_query = query
        for keyword in command_keywords:
            temp_query = temp_query.replace(keyword, "").strip()
        
        # 移除常见的前缀和后缀词
        prefix_words = ["帮我", "我要", "请", ""][::-1]  # 倒序以便正确移除
        suffix_words = ["应用", "程序", "软件", "吧", "一下", ""][::-1]
        
        for prefix in prefix_words:
            if prefix and temp_query.startswith(prefix):
                temp_query = temp_query[len(prefix):].strip()
                break
                
        for suffix in suffix_words:
            if suffix and temp_query.endswith(suffix):
                temp_query = temp_query[:-len(suffix)].strip()
                break
        
        return self._normalize_app_name(temp_query)
    
    def _normalize_app_name(self, app_name):
        """标准化应用名称"""
        if not app_name:
            return ""
            
        # 应用名称映射
        for chinese_name, english_name in self.app_name_mappings.items():
            if chinese_name.lower() in app_name.lower():
                return english_name
        
        # 特殊处理：数字加浏览器（如"1号浏览器"）
        import re
        if re.match(r'\d+号浏览器', app_name):
            return "chrome"  # 默认为Chrome
            
        # 直接返回名称作为最后的选项
        return app_name
    
    def _extract_folder_info(self, query):
        """增强版文件夹信息提取，支持名称和位置提取"""
        # 移除命令关键词
        for keyword in self.command_patterns["create_folder"]["keywords"]:
            query = query.replace(keyword, "").strip()
        
        # 检查位置信息
        location = None
        for loc_keyword, loc_path in self.location_keywords.items():
            if f"在{loc_keyword}" in query:
                location = loc_path
                query = query.replace(f"在{loc_keyword}", "").strip()
                break
            elif f"到{loc_keyword}" in query:
                location = loc_path
                query = query.replace(f"到{loc_keyword}", "").strip()
                break
        
        # 检查是否包含"名为"、"叫做"、"命名为"等关键词
        if "名为" in query:
            parts = query.split("名为")
            if len(parts) > 1:
                folder_name = parts[1].strip()
                return folder_name, location
        elif "叫做" in query:
            parts = query.split("叫做")
            if len(parts) > 1:
                folder_name = parts[1].strip()
                return folder_name, location
        elif "命名为" in query:
            parts = query.split("命名为")
            if len(parts) > 1:
                folder_name = parts[1].strip()
                return folder_name, location
        elif "为" in query:
            # 尝试提取"创建文件夹为..."格式
            parts = query.split("为")
            if len(parts) > 1 and "创建" in parts[0]:
                folder_name = parts[1].strip()
                return folder_name, location
        
        # 如果没有明确指定名称，使用默认名称或剩余文本
        folder_name = query.strip() if query.strip() else "新建文件夹"
        return folder_name, location
    
    def _normalize_location(self, location):
        """标准化位置路径"""
        if not location:
            return "."
            
        # 位置映射
        for loc_keyword, loc_path in self.location_keywords.items():
            if loc_keyword in location:
                return loc_path
                
        return location
    
    def _extract_search_term(self, query):
        """增强版搜索关键词提取，支持更多表达方式"""
        # 移除命令关键词
        for keyword in self.command_patterns["search_files"]["keywords"]:
            query = query.replace(keyword, "").strip()
        
        # 检查各种搜索模式
        search_patterns = ["关于", "包含", "带有", "含有", "的", "查找", "搜索"]
        for pattern in search_patterns:
            if pattern in query:
                parts = query.split(pattern)
                # 尝试从后半部分提取
                if len(parts) > 1:
                    potential_term = parts[1].strip()
                    if potential_term and not any(p in potential_term for p in search_patterns):
                        return potential_term
                # 尝试从前往后匹配（例如"搜索关键词"）
                for i, part in enumerate(parts):
                    if i > 0:
                        potential_term = part.strip()
                        if potential_term and not any(p in potential_term for p in search_patterns[search_patterns.index(pattern)+1:]):
                            return potential_term
        
        # 移除常见的前缀词
        prefix_words = ["帮我", "我要", "请", "给我"]
        for prefix in prefix_words:
            if query.startswith(prefix):
                query = query[len(prefix):].strip()
                break
        
        return query.strip()
    
    def _extract_volume_details(self, query):
        """增强版音量操作提取，支持具体数值和相对调整"""
        action = "set"
        value = None
        
        # 检查静音命令
        if any(keyword in query for keyword in ["静音", "消音", "静音模式", "关闭声音"]):
            return "mute", None
        elif any(keyword in query for keyword in ["取消静音", "取消消音", "打开声音"]):
            return "unmute", None
        
        # 检查增减命令
        increase_keywords = ["增大", "调高", "提高", "放大", "调大", "增加"]
        decrease_keywords = ["减小", "调低", "降低", "缩小", "调小", "减少"]
        
        if any(keyword in query for keyword in increase_keywords):
            action = "increase"
        elif any(keyword in query for keyword in decrease_keywords):
            action = "decrease"
        
        # 提取数值（百分比或具体值）
        import re
        # 匹配百分比格式：X% 或 X 百分比
        percent_match = re.search(r'(\d+)%', query) or re.search(r'(\d+)\s*百分比', query)
        if percent_match:
            value = int(percent_match.group(1))
            # 确保值在有效范围内
            value = max(0, min(100, value))
        else:
            # 匹配具体数值
            number_match = re.search(r'(\d+)', query)
            if number_match:
                value = int(number_match.group(1))
                # 确保值在有效范围内
                value = max(0, min(100, value))
        
        # 特殊处理：最大/最小
        if any(keyword in query for keyword in ["最大", "最高", "满"]):
            action = "set"
            value = 100
        elif any(keyword in query for keyword in ["最小", "最低"]):
            action = "set"
            value = 0
        
        return action, value
    
    def _extract_brightness_details(self, query):
        """增强版亮度操作提取，支持具体数值和相对调整"""
        action = "set"
        value = None
        
        # 检查增减命令
        increase_keywords = ["增大", "调高", "提高", "调亮", "调大", "亮一点", "亮点"]
        decrease_keywords = ["减小", "调低", "降低", "调暗", "调小", "暗一点", "暗点"]
        
        if any(keyword in query for keyword in increase_keywords):
            action = "increase"
        elif any(keyword in query for keyword in decrease_keywords):
            action = "decrease"
        
        # 提取数值（百分比或具体值）
        import re
        # 匹配百分比格式：X% 或 X 百分比
        percent_match = re.search(r'(\d+)%', query) or re.search(r'(\d+)\s*百分比', query)
        if percent_match:
            value = int(percent_match.group(1))
            # 确保值在有效范围内
            value = max(0, min(100, value))
        else:
            # 匹配具体数值
            number_match = re.search(r'(\d+)', query)
            if number_match:
                value = int(number_match.group(1))
                # 确保值在有效范围内
                value = max(0, min(100, value))
        
        # 特殊处理：最大/最小
        if any(keyword in query for keyword in ["最大", "最高", "最亮"]):
            action = "set"
            value = 100
        elif any(keyword in query for keyword in ["最小", "最低", "最暗"]):
            action = "set"
            value = 0
        
        return action, value
    
    def _extract_file_operation_params(self, query, command_type):
        """提取文件操作相关参数"""
        params = {}
        
        # 移除命令关键词
        for keyword in self.command_patterns[command_type]["keywords"]:
            query = query.replace(keyword, "").strip()
        
        # 根据命令类型提取不同参数
        if command_type == "navigate_folder":
            # 提取要进入的文件夹路径
            for loc_keyword, loc_path in self.location_keywords.items():
                if loc_keyword in query:
                    params["folder_path"] = loc_path
                    break
            if "folder_path" not in params:
                params["folder_path"] = query.strip() or "."
                
        elif command_type == "delete_file":
            # 提取要删除的文件名
            params["file_name"] = query.strip()
            
        elif command_type in ["copy_file", "move_file"]:
            # 提取源文件和目标位置
            # 检查是否包含"到"、"到...目录"等关键词
            if "到" in query:
                parts = query.split("到")
                if len(parts) > 1:
                    params["source"] = parts[0].strip()
                    target = parts[1].strip()
                    # 标准化目标位置
                    for loc_keyword, loc_path in self.location_keywords.items():
                        if loc_keyword in target:
                            params["target"] = loc_path
                            break
                    else:
                        params["target"] = target
            else:
                # 仅提供了源文件
                params["source"] = query.strip()
                
        elif command_type == "rename_file":
            # 提取原文件名和新文件名
            # 检查是否包含"为"、"改名为"等关键词
            rename_patterns = ["为", "改名为", "命名为"]
            for pattern in rename_patterns:
                if pattern in query:
                    parts = query.split(pattern)
                    if len(parts) > 1:
                        params["old_name"] = parts[0].strip()
                        params["new_name"] = parts[1].strip()
                        break
            
        return params
    
    def _extract_text_to_input(self, query):
        """提取要输入的文本内容"""
        # 移除命令关键词
        for keyword in self.command_patterns["send_keys"]["keywords"]:
            query = query.replace(keyword, "").strip()
        
        # 移除常见的前缀词
        prefix_words = ["帮我", "我要", "请", "给我"]
        for prefix in prefix_words:
            if query.startswith(prefix):
                query = query[len(prefix):].strip()
                break
                
        return query.strip()
    
    def _extract_url(self, query):
        """提取要访问的URL或网站名称"""
        # 移除命令关键词
        for keyword in self.command_patterns["open_url"]["keywords"]:
            query = query.replace(keyword, "").strip()
        
        # 检查是否已经是完整URL
        import re
        url_pattern = r'(https?://)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)'
        url_match = re.search(url_pattern, query)
        if url_match:
            url = url_match.group(0)
            # 如果没有协议前缀，添加http://
            if not url.startswith(('http://', 'https://')):
                url = 'http://' + url
            return url
        
        # 对于网站名称，尝试转换为URL
        site_mappings = {
            "百度": "https://www.baidu.com",
            "谷歌": "https://www.google.com",
            "必应": "https://www.bing.com",
            "淘宝": "https://www.taobao.com",
            "京东": "https://www.jd.com",
            "知乎": "https://www.zhihu.com",
            "微博": "https://www.weibo.com",
            "B站": "https://www.bilibili.com",
            "哔哩哔哩": "https://www.bilibili.com"
        }
        
        for site_name, site_url in site_mappings.items():
            if site_name in query:
                return site_url
        
        # 如果都不是，直接使用搜索
        return f"https://www.baidu.com/s?wd={query}"
    
    def _extract_calculation_expression(self, query):
        """增强版计算表达式提取，支持更多数学符号和复杂表达式"""
        # 移除计算关键词
        for keyword in self.command_patterns["calculator"]["keywords"]:
            query = query.replace(keyword, "").strip()
        
        # 替换中文数学符号和表达式
        symbol_mappings = {
            "加": "+",
            "加上": "+",
            "之和": "+",
            "减": "-",
            "减去": "-",
            "之差": "-",
            "乘": "*",
            "乘以": "*",
            "之积": "*",
            "除": "/",
            "除以": "/",
            "之商": "/",
            "等于": "",  # 移除等于，只保留表达式部分
            "等于多少": "",
            "等于几": "",
            "等于啥": "",
            "是多少": "",
            "是几": "",
            "结果是什么": "",
            "的结果": "",
            "等于多少啊": "",
            "等于几啊": "",
            "等于什么": "",
            "总和": "+",
            "总和是": "+",
            "总和是多少": "+",
            "差是": "-",
            "差是多少": "-",
            "积是": "*",
            "积是多少": "*",
            "商是": "/",
            "商是多少": "/",
            "的平方": "**2",
            "平方": "**2",
            "的立方": "**3",
            "立方": "**3",
            "的平方根": "**0.5",
            "平方根": "**0.5",
            "开根号": "**0.5",
            "根号": "**0.5"
        }
        
        # 替换符号，使用正则表达式确保最长匹配优先
        import re
        pattern = '|'.join(sorted(re.escape(key) for key in symbol_mappings.keys() if key), key=len, reverse=True)
        query = re.sub(pattern, lambda m: symbol_mappings[m.group(0)], query)
        
        # 处理常见的数字描述（如：三加四）
        number_words = {
            "零": "0", "一": "1", "二": "2", "三": "3", "四": "4",
            "五": "5", "六": "6", "七": "7", "八": "8", "九": "9",
            "十": "10", "百": "100", "千": "1000", "万": "10000"
        }
        
        for word, num in number_words.items():
            query = query.replace(word, num)
        
        return query.strip()
    
    def _calculate(self, expression):
        """增强版数学计算，支持更多数学函数和复杂表达式"""
        import re
        import math
        
        # 过滤表达式，只保留安全的字符
        safe_expr = re.sub(r'[^\d\+\-\*\/\.\(\)\s\*\*]', '', expression)
        
        # 安全地计算表达式，使用有限的命名空间
        try:
            # 定义安全的数学函数和常量
            safe_math = {
                'sin': math.sin, 'cos': math.cos, 'tan': math.tan,
                'asin': math.asin, 'acos': math.acos, 'atan': math.atan,
                'sqrt': math.sqrt, 'log': math.log, 'log10': math.log10,
                'exp': math.exp, 'abs': abs,
                'pi': math.pi, 'e': math.e,
                'floor': math.floor, 'ceil': math.ceil, 'round': round
            }
            
            # 执行计算
            result = eval(safe_expr, {'__builtins__': {}}, safe_math)
            
            # 处理浮点数精度问题
            if isinstance(result, float) and result.is_integer():
                return int(result)
            elif isinstance(result, float):
                # 保留合适的小数位数
                return round(result, 8)
            return result
        except Exception as e:
            # 尝试简化表达式再计算
            try:
                # 移除多余的空格和括号
                simplified = re.sub(r'\s+', '', safe_expr)
                simplified = re.sub(r'\((\d+)\)', r'\1', simplified)  # 移除数字周围的括号
                result = eval(simplified, {'__builtins__': {}}, safe_math)
                return result
            except:
                raise ValueError("无法计算的表达式")
    
    def _is_keyword_match(self, query, keywords, is_speech=False, min_similarity=0.85):
        """检查查询中是否包含关键词，支持语音识别误差处理
        
        Args:
            query: 待检查的查询文本
            keywords: 关键词列表
            is_speech: 是否为语音输入
            min_similarity: 语音模式下的最小相似度阈值
            
        Returns:
            是否匹配成功
        """
        if not is_speech:
            # 文本模式下使用精确匹配
            return any(keyword in query for keyword in keywords)
        
        # 语音模式下使用相似度匹配
        try:
            import difflib
            
            # 1. 先尝试精确匹配
            for keyword in keywords:
                if keyword in query:
                    return True
            
            # 2. 尝试分词匹配（处理语音识别可能的断句问题）
            query_words = query.split()
            for keyword in keywords:
                keyword_words = keyword.split()
                if all(any(word in q_word for q_word in query_words) for word in keyword_words):
                    return True
            
            # 3. 使用模糊匹配算法
            for keyword in keywords:
                # 计算关键词和查询文本的相似度
                similarity = difflib.SequenceMatcher(None, keyword, query).ratio()
                if similarity >= min_similarity:
                    return True
                
                # 也检查关键词是否是查询的子序列（允许中间有其他词）
                if self._is_subsequence(keyword, query):
                    # 计算子序列匹配的加权相似度
                    len_ratio = len(keyword) / len(query)
                    # 子序列相似度 = 基本相似度 * 长度比例
                    weighted_similarity = min_similarity * (0.7 + 0.3 * len_ratio)
                    if similarity >= weighted_similarity:
                        return True
            
            return False
            
        except ImportError:
            # 如果没有difflib模块，回退到基本匹配
            return any(keyword in query for keyword in keywords)
        except Exception:
            # 出错时回退到基本匹配
            return any(keyword in query for keyword in keywords)
    
    def _is_subsequence(self, pattern, text):
        """检查pattern是否是text的子序列（允许中间有其他字符）"""
        it = iter(text)
        return all(c in it for c in pattern)


class SimpleCommandParser:
    """简单命令解析器，用于在没有LLM API或本地模型时提供基础命令解析功能"""
    def __init__(self):
        # 基础命令模式映射
        self.command_patterns = {
            "open_application": {
                "keywords": ["打开", "启动", "运行", "开启", "调出"],
                "response": "正在打开{param}",
                "priority": 1
            },
            "close_application": {
                "keywords": ["关闭", "退出", "关掉", "关闭掉"],
                "response": "正在关闭{param}",
                "priority": 1
            },
            "create_folder": {
                "keywords": ["创建文件夹", "新建文件夹", "建个文件夹"],
                "response": "正在创建文件夹{param}",
                "priority": 2
            },
            "list_files": {
                "keywords": ["查看目录", "显示目录", "列出文件", "查看文件", "查看当前目录", "当前目录"],
                "response": "正在列出目录内容",
                "priority": 2
            },
            "control_volume": {
                "keywords": ["音量", "声音", "调音量", "调整声音"],
                "response": "正在调整音量",
                "priority": 1
            },
            "system_info": {
                "keywords": ["系统信息", "电脑配置", "查看配置"],
                "response": "正在获取系统信息",
                "priority": 2
            },
            "screenshot": {
                "keywords": ["截图", "截屏", "拍照", "保存截图"],
                "response": "准备截图",
                "priority": 1
            },
            "calculator": {
                "keywords": ["计算", "算", "等于", "计算器"],
                "response": "计算中...",
                "priority": 1
            }
        }
        
        # 基础应用名称映射
        self.app_name_mappings = {
            "浏览器": "chrome",
            "谷歌浏览器": "chrome",
            "火狐": "firefox",
            "ie": "iexplore",
            "edge": "msedge",
            "记事本": "notepad",
            "命令行": "cmd",
            "命令提示符": "cmd",
            "终端": "cmd",
            "powershell": "powershell",
            "计算器": "calc",
            "文件资源管理器": "explorer",
            "资源管理器": "explorer"
        }
    
    def process_query(self, query, is_speech=False):
        """处理用户查询，支持语音识别参数
        
        Args:
            query: 用户输入的查询文本
            is_speech: 是否为语音输入
            
        Returns:
            包含命令类型和参数的字典
        """
        query = query.strip().lower()
        
        # 处理特殊命令
        if query in ["退出", "停止", "关闭", "结束"]:
            return {"command": "exit", "response": "正在退出程序", "params": {}}
        
        if query in ["帮助", "帮助我", "怎么用", "使用说明"]:
            return {"command": "help", "response": "以下是可用的命令...", "params": {}}
        
        # 匹配命令模式
        matched_commands = []
        
        for command_type, pattern_info in self.command_patterns.items():
            # 使用关键词匹配
            if any(keyword in query for keyword in pattern_info["keywords"]):
                # 提取参数（简单实现）
                params = self._extract_params(query, command_type, is_speech)
                
                # 计算匹配得分（简化版）
                score = len(pattern_info["keywords"]) * 0.1 + pattern_info["priority"] * 0.2
                
                matched_commands.append({
                    "command": command_type,
                    "score": score,
                    "priority": pattern_info["priority"],
                    "params": params,
                    "response": pattern_info["response"].format(**params)
                })
        
        # 按得分和优先级排序
        if matched_commands:
            matched_commands.sort(key=lambda x: (x["score"], x["priority"]), reverse=True)
            best_match = matched_commands[0]
            
            return {
                "command": best_match["command"],
                "response": best_match["response"],
                "params": best_match["params"]
            }
        
        # 未匹配到任何命令
        return {"command": "unknown", "response": "抱歉，我无法理解您的命令", "params": {}}
    
    def _extract_params(self, query, command_type, is_speech=False):
        """提取命令参数
        
        Args:
            query: 用户查询
            command_type: 命令类型
            is_speech: 是否为语音输入
            
        Returns:
            参数字典
        """
        params = {"param": ""}
        
        if command_type == "open_application":
            # 提取应用名称
            for app_name, app_cmd in self.app_name_mappings.items():
                if app_name in query:
                    params["param"] = app_name
                    params["app_name"] = app_name
                    params["app_cmd"] = app_cmd
                    break
            else:
                # 如果没有找到预定义的应用，尝试提取最后的名词
                words = query.split()
                params["param"] = words[-1] if words else ""
        
        elif command_type == "close_application":
            # 提取应用名称
            for app_name, app_cmd in self.app_name_mappings.items():
                if app_name in query:
                    params["param"] = app_name
                    params["app_name"] = app_name
                    params["app_cmd"] = app_cmd
                    break
        
        elif command_type == "create_folder":
            # 提取文件夹名称
            keywords = self.command_patterns["create_folder"]["keywords"]
            for keyword in keywords:
                if keyword in query:
                    # 提取关键词后面的内容作为文件夹名
                    folder_name = query.split(keyword)[-1].strip()
                    params["param"] = folder_name
                    params["folder_name"] = folder_name
                    break
        
        elif command_type == "control_volume":
            # 处理音量控制参数
            if any(word in query for word in ["增大", "调高", "提高", "变大"]):
                params["param"] = "up"
                params["action"] = "increase"
            elif any(word in query for word in ["减小", "调低", "降低", "变小"]):
                params["param"] = "down"
                params["action"] = "decrease"
            elif any(word in query for word in ["静音", "关闭"]):
                params["param"] = "mute"
                params["action"] = "mute"
            elif any(word in query for word in ["取消静音", "打开"]):
                params["param"] = "unmute"
                params["action"] = "unmute"
        
        elif command_type == "calculator":
            # 提取计算表达式
            keywords = self.command_patterns["calculator"]["keywords"]
            for keyword in keywords:
                query = query.replace(keyword, "").strip()
            params["param"] = query
            params["expression"] = query
        
        elif command_type == "list_files":
            # 提取目录参数（如果有）
            if any(keyword in query for keyword in ["当前目录", "当前文件夹"]):
                params["param"] = "当前目录"
                params["path"] = "."
        
        return params